﻿using System;

using Common.Base;

using GameCommon.ComponentInterfaces;
using GameCommon.ManagerInterfaces;

using Microsoft.Xna.Framework.Graphics;

using GlobalServices = GameCommon.Services.Service;
using Xna = Microsoft.Xna.Framework;

namespace Menu.Components
{
    internal class SpriteTexture : Texture, IUpdatable
    {
        private double elapsedTime;

        public SpriteTexture(string id, MenuComponentBase objectToCopy, Texture2D texture2D, int spriteCount, int fullWidth)
            : base(id, objectToCopy, texture2D)
        {
            this.FullWidth = fullWidth;
            this.SpriteCount = spriteCount;
            this.CopyTexture(objectToCopy);
        }

        public int SpriteCount { get; private set; }

        public int FullWidth { get; private set; }

        public int Time { get; set; }

        public Dimension SourceDimension { get; set; }

        public override void Draw(IDrawingManager manager, Xna.GameTime gameTime)
        {
            this.DrawingService.Draw(manager, this.Texture2D, this.Dimension, this.SourceDimension, this.Opacity, 1);
        }
        
        public void Update(Xna.GameTime gameTime)
        {
            this.elapsedTime += gameTime.ElapsedGameTime.Milliseconds;
            if (this.elapsedTime > this.Time)
            {
                this.elapsedTime = 0;

                this.SourceDimension.X += this.SourceDimension.Width;
                if (this.SourceDimension.X >= this.FullWidth)
                {
                    this.SourceDimension.X = 0;
                }
            }
        }

        private void CopyTexture(MenuComponentBase objectToCopy)
        {
            var tex = objectToCopy as Texture;
            if (tex == null)
            {
                throw new Exception();
            }

            this.HorizontalAlignment = tex.HorizontalAlignment;
            this.VerticalAlignment = tex.VerticalAlignment;
        }
    }
}